<?php

class Front extends Kernel {

    public function __construct() {
        parent::__construct();
        $theme = $this->getTheme();
        $this->v->init( APP_PATH . "/themes/front/{$theme}/", APP_TPL . "front/{$theme}/" );
        $this->themesURL = $this->setting[ 'weburl' ] . "/themes/front/{$theme}";
        $this->sort = $this->sort();
        $this->page = $this->get_page();
    }

    public function __destruct() {
        $content = ob_get_clean();
        // 压缩HTML代码
        if ( $this->setting[ 'is_formathtml' ] ) {
            $content = str_replace( array( "\r", "\n", "\t", "  " ), "", $content );
        }
        // 启用GZIP压缩
        if ( $this->setting[ 'is_gzip' ] && function_exists( 'ob_gzhandler' ) ) {
            ob_start( 'ob_gzhandler' );
        } else {
            ob_start();
        }
        exit( $content );
    }

    /*
     *  返回前台模板
     */
    private function getTheme() {
        $theme = $this->setting[ 'Theme' ];
        if ( $this->setting[ 'Theme' ] == 'random' ) {
            $list = list_dir( APP_PATH . "/themes/front/*" );
            $theme = array_rand( $list, 1 );
        }
        return $theme;
    }

    /*
     * 返回导航菜单
     *
     * @param $sub  是否显示子菜单
     */
    public function get_nav( $sub = false ) {
        $nav = unserialize( $this->setting[ 'nav' ] );
        $html = $current = "";
        $page = $this->Node()->dataTree( $this->page );
        $sort = array_merge( $this->sort( 'article', 0, 'dataTree' ), $page );
        foreach ( $sort as $v ) {
            $tmp[ $v[ 'title' ] ] = $v;
        }
        $sort = $tmp;
        unset( $tmp );

        foreach ( $nav as $k => $v ) {
            if ( $v[ 'url' ] == 'auto' ) {
                $current = '';
                $html .= $this->Node()->dataTreeLiUl( array( $k => $sort[ $k ] ) );
            } else {
                $target = $v[ 'target' ] ? ' target="_blank"' : '';
                $html .= "<li{$current}><a href=\"{$v[ 'url' ]}\"{$target} title=\"{$v[ 'title' ]}\">{$v[ 'title' ]}</a></li>\n";
            }
        }
        return $html;
    }

    /*
     *  返回gravatar头像
     *
     */
    public function gravatar( $email = '', $s = 32, $r = 'g' ) {
        $email = md5( strtolower( trim( $email ) ) );
        $grav_url = "http://www.gravatar.com/avatar/{$email}?s={$s}&r={$r}";
        return $grav_url;
    }

    /*
     *  读取文章的评论信息
     *
     *  @param $aid        文章编号  null 返回全部评论
     *  @param $limit      返回记录数 null 不限制
     */
    public function get_comment( $aid = null, $limit = null ) {
        if ( $aid != null ) {
            $this->model->table = 'comment';
            return $this->model->findAll( array( 'aid' => $aid ), 'id asc', null, $limit );
        }
        return $this->model->article_comment( $limit );
    }

    /*
     * 读取标签
     *
     * @param $id        文章ID  null 返回指定条数标签
     */
    public function getTag( $id = null ) {
        // 读取文章标签
        if ( $id != null ) {
            if ( $tag = $this->model->tag_id( $id ) ) {
                $tag = explode( ",", $tag );
            }
            return $tag;
        }

        $limit = $this->setting[ 'tag_num' ] ? $this->setting[ 'tag_num' ] : 20;
        $tags = $this->model->tag_limit( $limit );
        shuffle( $tags );
        $html = "";
        $tmp = array( 20, 15, 10, 5, 0 );
        foreach ( $tags as $v ) {
            $url = $this->url( 'tag', null, array( 'tag' => $v[ 'tag' ] ) );
            foreach ( $tmp as $a )
                if ( $v[ 'total' ] >= $a ) {
                    $size = $a / 5;
                    break;
                }
            $html .= "<li><a class=\"s{$size}\" href=\"{$url}\" title=\"{$v[ 'tag' ]}\">{$v[ 'tag' ]}</a></li>";
        }
        return $html;
    }

    public function Breadcrumbs( $result, $type = 3 ) {
        $html = "<span>当前位置: <a href=\"{$this->setting[ 'weburl' ]}\">首页</a>";
        if ( $type == 1 ) {
            $html .= $this->Node()->parentTree( $this->get_page(), $result[ 'sid' ], $result[ 'id' ] );
        } elseif ( $type == 2 ) {
            $html .= $this->Node()->parentTree( $this->sort, $result[ 'sid' ], -1, 'sort' );
        } else {
            $html .= $this->Node()->parentTree( $this->sort, $result[ 'sid' ], $result[ 'id' ], 'sort' );
        }
        $name = $type == 2 ? " > {$result[ 'title' ]}" : '';
        $html .= "{$name}</span>";
        return $html;
    }

    /*
     *  根据文章tag 读取相关文章
     *
     *  @param $tag        文章tag
     *  @param $id         排除指定ID的相关文章
     */
    public function get_related( $tag, $id ) {
        if ( !$tag ) {
            return $this->get_sort_article();
        }
        $limit = $this->setting[ 'related_num' ] ? $this->setting[ 'related_num' ] : 9;
        return $this->model->article_related( $tag, $id, $limit );
    }

    /*
     *  返回指定ID的文章内容
     *
     *  @param $id              文章id
     *  @param $content         1 返回文章内容 2 返回文章摘要 3 返回文章数组
     */
    public function get_id_archives( $id, $content = 1 ) {
        $this->model->table = 'article';
        $result = $this->model->find( array( 'id' => $id ) );
        if ( $content == 3 ) return $result;
        if ( $content == 2 ) return $this->get_excerpt( $result );
        return htmlspecialchars_decode( $result[ 'content' ] );
    }

    /*
     *  读取指定栏目下文章
     *
     *  @param $id     栏目ID
     *  @param $limit  返回数量
     *  @param $order  排序
     */
    public function get_sort_article( $id = null, $limit = 8, $order = 'isTop desc, oid desc, id desc' ) {
        $this->model->table = 'article';
        if ( null == $id ) {
            return $this->model->findAll( array( 'model' => 'article' ), $order, null, $limit );
        }
        $sid = $this->Node()->treeID( $this->sort, $id );
        $sid = implode( ',', $sid );
        return $this->model->findAll( "sid in ({$sid})", $order, null, $limit );
    }

    /*
     * 返回友情链接
     */
    public function getlink() {
        $link = $this->model->Cache()->get( 'link' );
        $html = "";
        foreach ( $link as $v ) {
            $title = $v[ 'info' ] ? $v[ 'info' ] : $v[ 'title' ];
            $html .= "<li><a href=\"{$v[ 'url' ]}\" target=\"_blank\" title=\"{$title}\">{$v[ 'title' ]}</a></li>";
        }
        return $html;
    }

    /*
     *  返回文章摘要
     */
    public function get_excerpt( $result, $html = false, $len = null ) {
        if ( $result[ 'excerpt' ] )
            return htmlspecialchars_decode( $result[ 'excerpt' ] );
        $tmp = htmlspecialchars_decode( $result[ 'content' ] );
        if ( stripos( $tmp, '<!--more-->' ) !== false ) {
            $arr = explode( '<!--more-->', $tmp );
            return $arr[ 0 ];
        }
        null == $len or $len = $this->setting[ 'excerpt_num' ];
        return htmlText( htmlspecialchars_decode( $result[ 'content' ] ), $len, $html );
    }

    # 404页面
    public function show_404() {
        $title = "没有找到 " . ( R( 'id' ) ? R( 'id' ) : R( 'alias' ) );
        $keywords = $this->setting[ 'webkey' ];
        $description = $this->setting[ 'webdesc' ];
        include $this->display( '404' );
        exit;
    }

    /*
     *  URL模式的构建函数
     *
     * @param @controller    控制器名称
     * @param @action    动作名称
     * @param @args    传递的参数，数组形式
     */
    public function url( $controller = null, $action = null, $args = null, $anchor = null ) {
        if ( $this->setting[ 'is_rewrite' ] ) {
            if ( $url = C( 'UrlRewrite' )->get_url( $controller, $action, $args, $anchor ) )
                return $url;
        }
        $url = $GLOBALS[ "url_path_base" ] . "?c={$controller}";
        if ( $action != null )
            $url .= "&a={$action}";
        if ( null != $args )
            foreach ( $args as $key => $arg )
                $url .= "&{$key}={$arg}";
        if ( null != $anchor )
            $url .= "#" . $anchor;
        return $this->setting[ 'weburl' ] . $url;
    }

    // 分类url
    public function sort_url( $arr, $a = null, $anchor = null ) {

        $args = array( 'id' => $arr[ 'id' ] );
        if ( $this->setting[ 'is_rewrite' ] && !empty( $arr[ 'alias' ] ) ) {
            $args[ 'alias' ] = $arr[ 'alias' ];
        }
        return $this->url( 'sort', $a, $args, $anchor );
    }

    // 文章url
    public function archives_url( $arr, $anchor = null, $a = null ) {
        if ( $arr[ 'model' ] == 'link' )
            return $arr[ 'alias' ];

        $args = array( 'id' => $arr[ 'id' ] );

        if ( $this->setting[ 'is_rewrite' ] ) {
            if ( !empty( $arr[ 'alias' ] ) )
                $args[ 'alias' ] = $arr[ 'alias' ];
            $args[ 'date' ] = $arr[ 'dateline' ];
        }

        return $this->url( 'archives', $a, $args, $anchor );
    }
}